package com.example.tests;

import java.awt.AWTException;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Properties;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.RandomStringUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

import com.example.fw.ApplicationManager;
import com.google.common.io.Files;

public class TestBase {
	
	protected static ApplicationManager app;
	private int checkCounter;
	private int checkFrequency;

	@BeforeTest
	public void setUp() throws Exception {
		String configFile = System.getProperty("configFile", "application.properties");
		Properties properties = new Properties();
		properties.load(new FileReader(configFile));
		app = new ApplicationManager(properties);
		String ftpConfigFile = properties.getProperty("ftp.configFile");
		app.getFtpHelper().backupFile(ftpConfigFile, ftpConfigFile + ".bak");
		app.getFtpHelper().uploadFile(new FileInputStream(ftpConfigFile), ftpConfigFile);
		app.getFtpHelper().closeFtpConnection();
		checkCounter = 0;
		checkFrequency = Integer.parseInt(properties.getProperty("check.frequency", "0"));
	}

	protected boolean wantToCheck() {
		checkCounter++;
		if (checkCounter > checkFrequency) {
			checkCounter = 0;
			return true;
		} else {
			return false;
		}
	}
	
	@AfterTest
	public void tearDown() throws Exception {
		app.stop();
	}
	
	@AfterMethod
	public void takeScreenshotOnTestFalure(ITestResult result) throws HeadlessException, IOException, AWTException{
		if (result.isSuccess()){
			return;
		}
		File screenshot = takesScreenShot();
		//takesScreenShotFullScreen(result);
		if (screenshot == null){
			Reporter.log("Can't take pageshot");
		} else {
			File target = File.createTempFile("screenshot", ".png", new File("."));
			Files.copy(screenshot, target);
			Reporter.log("<a href = '" + target.getAbsolutePath() + "'>" + target.getName() + "</a>");
		}
	}
	  
    private File takesScreenShot() {
		if (app.driver instanceof TakesScreenshot){
			File screenshot = ((TakesScreenshot) app.driver).getScreenshotAs(OutputType.FILE);
			return screenshot;
		}
		return null;
	}

    private void takesScreenShotFullScreen(ITestResult result) throws IOException, HeadlessException, AWTException {
    	BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    	ImageIO.write(image, "png", new File(result.getMethod().getMethodName() + "/screenshot.png"));
	}
    
	public static String generateRandomString(int textLength) {
    	Random rnd = new Random();
		if (rnd.nextInt(10) == 0) {
			return "";
			} else {
				return RandomStringUtils.random(textLength, "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz");
			}
	}
      
    public static String generateTextSymbols(int textLength) {
	    StringBuilder textLatinSymbols = new StringBuilder("Z");
	    Random rnd = new Random();
	    while (textLatinSymbols.length() < textLength) {
	        int stringLength = rnd.nextInt(20);
	        if (stringLength > 0) {
	        	textLatinSymbols.append(" ").append(RandomStringUtils.random(stringLength,
	                      "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"));
	        	}
	        }
	    if (textLatinSymbols.length() > textLength) {
	    	textLatinSymbols.delete(textLength, textLatinSymbols.length());
	    	}
	    return textLatinSymbols.toString();
	}
	  
	public static String generateRandomStringWithNumbers(int stringLength) {
		Random rnd = new Random();
		if (rnd.nextInt(10) == 0) {
			return "";
			} else {
				return RandomStringUtils.randomNumeric(stringLength);
			}
	}

	public static String[] generateRandomDate() {
		Random rnd = new Random();
		String[] date = {"-", "-", ""};
		if (rnd.nextInt(10) != 0) {
			GregorianCalendar gc = new GregorianCalendar();
			int year = randBetween(1900, 2013);
			int dayOfYear = randBetween(1, gc.getActualMaximum(Calendar.DAY_OF_YEAR));
			gc.set(Calendar.YEAR, year);
			gc.set(Calendar.DAY_OF_YEAR, dayOfYear);
			String[] months = {"January", "February", "March", "April", "May", "June", "July", 
					  "August", "September", "October", "November", "December"};
			date[0] = Integer.toString(gc.get(Calendar.DAY_OF_MONTH));
			date[1] = months[gc.get(Calendar.MONTH)];
			date[2] = Integer.toString(gc.get(Calendar.YEAR));
			}
		return date;
	}

	public static int randBetween(int start, int end) {
		return start + (int)Math.round(Math.random() * (end - start));
	}
}
